using Blog2025.Application.Common;
using Blog2025.Application.Contracts.Interface;
using Blog2025.Domain.Entities.App;
using Blog2025.Domain.Repositories;

namespace Blog2025.Application.Services;

public class AuthService
{
    private readonly IRepository<AppUser> _userRepo;
    private readonly IRepository<AppRole> _roleRepo;
    private readonly IJwtService _jwtService;

    public AuthService(IRepository<AppUser> userRepo, IRepository<AppRole> roleRepo,IJwtService jwtService)
    {
        _userRepo = userRepo;
        _roleRepo = roleRepo;
        _jwtService=jwtService;
    }

    public async Task RegisterAsync(string username, string password)
    {
        // 1. 检查用户名是否存在
        var exists = (await _userRepo.GetAllAsync()).Any(u => u.Username == username);
        if (exists) throw new Exception("用户名已存在");

        // 2. 生成盐和加密密码
        var salt = Guid.NewGuid().ToString("N");
        var hashedPwd = HashPassword(password, salt);

        // 3. 分配默认角色
        var defaultRole = (await _roleRepo.GetAllAsync()).FirstOrDefault(r => r.RoleName == "User");
        var user = new AppUser
        {
            Username = username,
            Password = hashedPwd,
            Salt = salt
        };
        if (defaultRole != null)
            user.AssignRole(defaultRole);

        // 4. 保存
        await _userRepo.CreateAsync(user);
    }
    public async Task<ApiResult> LoginAsync(string username, string password)
    {
        var user = (await _userRepo.GetAllAsync()).FirstOrDefault(u => u.Username == username);
        if (user == null)
        {
            return ApiResult.Fail(404,"账号不存在");
        }

        var hashedPwd = HashPassword(password, user.Salt);
        if (user.Password != hashedPwd)
        {
            return ApiResult.Fail(404,"账号密码无效");
        }

        var token=_jwtService.GenerateToken(user.Id,username);
        return ApiResult.Success(token,"登录成功");
    }

    private string HashPassword(string password, string salt)
    {
        // 简单示例，实际请用更安全的哈希算法
        using var sha256 = System.Security.Cryptography.SHA256.Create();
        var bytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
        var hash = sha256.ComputeHash(bytes);
        return Convert.ToBase64String(hash);
    }


}